package dao

import (
	"cms/model"
	"encoding/json"
	"github.com/wdaglb/korm"
	"reflect"
)

// GetConfig 获取所有配置节点
func GetConfig() model.AllConfig {
	config := &model.AllConfig{}
	values := make([]model.Config, 0)
	db := korm.NewContext()
	if db.Model(&values).Select().Error != nil {
		return *config
	}
	refValue := reflect.ValueOf(config).Elem()
	refType := reflect.TypeOf(config).Elem()
	for _, c := range values {
		dvt := refValue.FieldByName(c.Name)
		field, ok := refType.FieldByName(c.Name)
		if !ok {
			continue
		}
		dvt.Set(reflect.New(field.Type.Elem()))
		dv := dvt.Interface()

		_ = json.Unmarshal(c.Value, &dv)
	}
	return *config
}

func SetConfig(config model.AllConfig) error {
	refType := reflect.TypeOf(config)
	refValue := reflect.ValueOf(config)
	numField := refValue.NumField()
	db := korm.NewContext()
	for i := 0; i < numField; i++ {
		row := &model.Config{}
		field := refType.Field(i)
		row.Name = field.Name
		dataValue, err := json.Marshal(refValue.Field(i).Interface())
		if err != nil {
			return err
		}

		row.Value = dataValue
		if db.Model(model.Config{}).Where("Name", row.Name).Exist() {
			err = db.Model(&row).Where("Name", row.Name).Update()
		} else {
			err = db.Model(&row).Create()
		}
		if err != nil {
			return err
		}
	}
	return nil
}
